# 使用 Ubuntu 作为基础镜像
FROM ubuntu:22.04 as builder

# 设置构建参数
ARG PUBLIC_IP
ARG BACKEND_PORT=5000

# 设置时区
ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

# 安装基础工具和依赖
RUN apt-get update && apt-get install -y \
    curl \
    gnupg \
    lsb-release \
    git \
    graphicsmagick \
    procps \
    && rm -rf /var/lib/apt/lists/*

# 安装 Node.js 20.x
RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
    && apt-get install -y nodejs \
    && npm install -g npm@latest

# 创建工作目录
WORKDIR /build

# 设置构建环境变量
ENV GENERATE_SOURCEMAP=false
ENV DISABLE_ESLINT_PLUGIN=true
ENV NODE_ENV=production
ENV CI=false
ENV PUBLIC_URL=/
ENV REACT_APP_API_URL=http://${PUBLIC_IP:-localhost}:${BACKEND_PORT}

# 复制前端文件
COPY frontend/package*.json ./frontend/
RUN cd frontend \
    && npm config set registry https://registry.npmmirror.com \
    && npm install --no-audit --no-fund

COPY frontend ./frontend
RUN cd frontend \
    && npm run build

# 复制后端文件
COPY backend/package*.json ./backend/
RUN cd backend \
    && npm config set registry https://registry.npmmirror.com \
    && npm install --no-audit --no-fund

COPY backend ./backend

# 第二阶段：运行环境
FROM ubuntu:22.04

# 设置构建参数
ARG PUBLIC_IP
ARG BACKEND_PORT=5000

# 设置时区
ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

# 安装基础工具和依赖
RUN apt-get update && apt-get install -y \
    curl \
    gnupg \
    lsb-release \
    git \
    graphicsmagick \
    procps \
    && rm -rf /var/lib/apt/lists/*

# 安装 Node.js 20.x
RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
    && apt-get install -y nodejs \
    && npm install -g npm@latest

# 创建工作目录
WORKDIR /app

# 创建必要的目录
RUN mkdir -p /app/uploads /app/backend /app/backend/public

# 从构建阶段复制文件
COPY --from=builder /build/backend /app/backend
COPY --from=builder /build/frontend/build /app/backend/public

# 重新安装后端依赖
RUN cd /app/backend \
    && npm config set registry https://registry.npmmirror.com \
    && npm install --production --no-audit --no-fund \
    && npm install express --no-audit --no-fund

# 设置权限
RUN chmod 755 /app/uploads \
    && chmod 755 /app/backend \
    && chmod 755 /app/backend/public

# 设置环境变量
ENV NODE_ENV=production
ENV HOST=0.0.0.0
ENV PORT=${BACKEND_PORT}
ENV PUBLIC_IP=${PUBLIC_IP:-localhost}
ENV REACT_APP_API_URL=http://${PUBLIC_IP:-localhost}:${BACKEND_PORT}

# 暴露端口
EXPOSE ${BACKEND_PORT}

# 启动脚本
COPY docker-entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/docker-entrypoint.sh

# 设置容器启动命令
CMD ["docker-entrypoint.sh"] 